package sg.edu.nus.iss.billing.service.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import sg.edu.nus.iss.billing.common.dataHandling.DataFile;

public class DataLoaderServiceImpl implements IDataLoaderService{

	HashMap<String, Object> dataFile = new HashMap<String, Object>(); 
	@Override
	public void clearData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteFile(String fileName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Object findFile(String fileName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void loadData() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean loadFactoryData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void saveFile(String fileName, Object obj) throws FileNotFoundException, IOException {
		
		byte[] byteArray = generateByteArray(fileName, obj);
		if(byteArray != null){ 
			
		}
		
	}
	/*
	 * If the file wants to put, fileName = "memberIDGenerate" , filePath="wheretoPut", whichObjtoPut
	 * if file wants to retrieve, which file wants to retrieve, from wheretoRetrieve,  
	 */
	/*
	 * this method is just to change the given input into byteArray:
	 */
	public byte[] generateByteArray(String fileName, Object obj)throws IOException, FileNotFoundException{
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] byteArray = new byte[]{};
		String filePath = filePathAutoGenerator(fileName);
		if(notEmpty(filePath)&&notEmpty(fileName)){
			if(obj != null){//wants to insert
				
			}else{ //wants to retrieve according by filePath and fileName
				
				
				File file = new File(filePath);
				try{
					FileInputStream fis = new FileInputStream(file);
					byte[] buf = new byte[1024];
					for(int readNum; (readNum = fis.read(buf)) != -1;){
						bos.write(buf, 0, readNum);
					}
					byteArray = bos.toByteArray();
					return byteArray;
					
				}catch (FileNotFoundException e) {
					System.out.println(e.getMessage());
				}
			}
			return byteArray;
		}
		
		else{
			return null;
		}
	}

	private String filePathAutoGenerator(String fileName){
		
		StringBuffer sb = new StringBuffer();
		sb.append(DataFile.filePath+"\\"+fileName);
		return sb.toString(); 
	}
	
	public static boolean notEmpty(String s) {
	 return (s != null && s.length() > 0);
	}
}
